package com.godpaper.chessGameHall.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.godpaper.chessGameHall.events.TryConnectServerEvent;
	import com.godpaper.chessGameHall.model.ConfigModelLocator;
	import com.godpaper.chessGameHall.model.ConnectionModelLocator;
	import com.godpaper.chessGameHall.view.components.LoginViewer;
	
	import flash.display.DisplayObject;
	
	import it.gotoandplay.smartfoxserver.SFSEvent;
	
	import mx.core.Application;
	import mx.managers.PopUpManager;
	import mx.rpc.IResponder;
	
	public class TryConnectServerCommand extends CommandBase implements ICommand, IResponder
	{
		private var tryConnectServerEvent:TryConnectServerEvent;
		private var connectionModel:ConnectionModelLocator = ConnectionModelLocator.getInstance();	
		private var configModel:ConfigModelLocator = ConfigModelLocator.getInstance();
		public function TryConnectServerCommand()
		{
			super();
		}
		
		override public function execute(event:CairngormEvent):void
		{
			tryConnectServerEvent = TryConnectServerEvent(event);
			
			this.sfClient.addEventListener(SFSEvent.onConnection,connectionHandler);
			
			this.sfClient.connect( tryConnectServerEvent.ip,tryConnectServerEvent.port );
		}
		/**
		 * Handler Server connection
		 * @param SFSEvent
		 */		
		private function connectionHandler(event:SFSEvent):void
		{
			trace("connectionHandler success:",event.params.success);
			if(event.params.success)
			{
				PopUpManager.removePopUp( Application.application.iConnectionViewer );
				Application.application.iConnectionViewer = null;
				Application.application.frameRate = 31;
				Application.application.iLoginViewer = PopUpManager.createPopUp( Application.application as DisplayObject,LoginViewer,true);
				PopUpManager.centerPopUp( Application.application.iLoginViewer );
			}else
			{
//				(ViewLocator.getInstance().getViewHelper("connectionViewHelper") as ConnectionViewHelper)
				connectionModel.connectionStatus = "Failed connecting to " + configModel.sfsConfigVO.ip + ":" + configModel.sfsConfigVO.port;
			}
		}
	}
}